<?php
namespace app\common\model;
use x\Xbase;
class ArticleCat extends Xbase
{
    /**
     * 返回分类下的所有子分类,  无限极没有分页, 重新组装数据结构, 有分类的深度
     * @param number $id 分类id
     */
    public function allSubCat($id = 0,$data = []){

        static $temp = [];
        $sql = "select * from article_cat where parent_id=? order by sort desc";
        $rs = $this->db->query($sql,[$id]);
        foreach($rs as $val){
            $val['depath'] = substr_count($val['cat_tree'], ",")-1;
            $temp[] = $val;
            $this->allSubCat($val['id']);
        }
        return $temp;
    }

    /**
     * 创建自己的树结构
     * @param number $parent_id 父ID
     * @return string 树结构
     */
    public function buildTree($parent_id = 0){
        $temp = ",0,";
        if( $parent_id!=0 ){
            $temp = $this->db->query("select cat_tree from article_cat where id=?",[$parent_id],1);
            $temp = $temp['cat_tree'].$parent_id.",";
        }
        return $temp;
    }

    //获取所有子分类
    public function getAllchildCat($id){
        $rs = $this->db->query('select * from article_cat where cat_tree like ?',['%,' . $id .',%']);
        return array_column($rs,'id');
    }

    //修改级别
    public function editLevel($new_tree){
        $list = $this->db->query("select * from article_cat where cat_tree like ?",[$new_tree.'%']);
        foreach ($list as $k => $v) {
            $d = [];
            $level = count(explode(',',$v['cat_tree'])) - 3;
            $d['level'] = $level;
            $this->db->update('article_cat',$d,['id = ?',[$v['id']]]);
        }
        return true;
    }

}
